import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lily
 * Date: 2024-10-08
 * Time: 13:04
 */
public class CombinationSum {
    int aim;
    List<Integer> path;
    List<List<Integer>> ret;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        path = new ArrayList<>();
        ret = new ArrayList<>();
        aim = target;
        combinationSum_dfs(candidates, 0, 0);
        return ret;
    }

    private void combinationSum_dfs(int[] nums, int pos, int sum) {
        if (sum == aim) {
            ret.add(new ArrayList<>(path));
            return;
        }
        if (sum > aim || pos == nums.length)
            return;

        for (int i = pos; i < nums.length; i++) {
            sum += nums[i];
            path.add(nums[i]);
            combinationSum_dfs(nums, i, sum);
            sum -= nums[i];
            path.remove(path.size()-1);
        }
    }
}
